﻿using HardcoreGame.Common.Players;
using Microsoft.Xna.Framework;
using System.Collections.Generic;
using Terraria;
using Terraria.Audio;
using Terraria.ID;
using Terraria.Localization;
using Terraria.ModLoader;

namespace HardcoreGame.Content.Items.Consumables.Healing
{
    public class Bandage : ModItem
    {
        public override void SetDefaults()
        {
            Item.width = 24;
            Item.height = 24;
            Item.maxStack = Item.CommonMaxStack;
            Item.consumable = true;
            Item.useTime = 90; 
            Item.useAnimation = 90;
            Item.useStyle = ItemUseStyleID.HoldUp;
            Item.UseSound = SoundID.Item4;
            Item.value = Item.buyPrice(0, 0, 50); 
            Item.rare = ItemRarityID.White;
            Item.noMelee = true;
        }

        public override bool? UseItem(Player player)
        {
            if (player.whoAmI == Main.myPlayer)
            {
                var modPlayer = player.GetModPlayer<FracturePlayer>();
                var injuredLimbs = new List<FractureLocation>();
                var treatableLimbs = new FractureLocation[] {
                    FractureLocation.LeftArm,
                    FractureLocation.RightArm,
                    FractureLocation.LeftLeg,
                    FractureLocation.RightLeg
                };

                foreach (var location in treatableLimbs)
                {
                    if (modPlayer.GetPartHealth(location) < 1f)
                    {
                        injuredLimbs.Add(location);
                    }
                }

                if (injuredLimbs.Count == 0)
                {
                    Main.NewText(Language.GetTextValue("Mods.HardcoreGame.Message.NoLimbInjury"), Color.Orange);
                    return false;
                }

                FractureLocation selectedLimb = injuredLimbs[Main.rand.Next(injuredLimbs.Count)];
                float currentHealth = modPlayer.GetPartHealth(selectedLimb);
                float healAmount = MathHelper.Clamp(0.12f, 0f, 1f - currentHealth); 

                modPlayer._partHealth[selectedLimb] = currentHealth + healAmount;               
                for (int i = 0; i < 8; i++)
                {
                    Dust.NewDust(player.position, player.width, player.height,
                        DustID.Cloud, 0, 0, 100, default, 0.8f);
                }

                SoundEngine.PlaySound(SoundID.Item4 with { Pitch = 0.5f });               
                return true;
            }
            return false;
        }

        public override void AddRecipes()
        {
            CreateRecipe()
                .AddIngredient(ItemID.Silk, 5) 
                .AddIngredient(ItemID.Gel, 10) 
                .AddTile(TileID.WorkBenches)
                .Register();
        }       
    }
}
